package cn.edu.imust.loginregisterdemo.login.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.edu.imust.loginregisterdemo.R;
import cn.edu.imust.loginregisterdemo.base.BaseFragment;
import cn.edu.imust.loginregisterdemo.login.model.Code;
import cn.edu.imust.loginregisterdemo.login.model.User;
import cn.edu.imust.loginregisterdemo.home.view.MainActivity;
import cn.edu.imust.loginregisterdemo.utils.Utils;

public class UsernameLoginFragment extends BaseFragment {

    @BindView(R.id.et_username)
            EditText  etUsername;
    @BindView(R.id.et_password)
            EditText  etPassword;
    @BindView(R.id.et_pic_code)
            EditText  etPicCode;
    @BindView(R.id.iv_pic_code)
            ImageView ivPicCode;
    @BindView(R.id.tv_termOfService)
            TextView  tvTermOfService;
    @BindView(R.id.u_login)
            Button    uLogin;
    private String    currentName;
    private String    currentPassword;
    private String    realCode;
    private String    currentPicCode;
    private ProgressDialog pd;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_username_login, container, false);
        Bmob.initialize(getContext(), "33452dfaa0b4f1b9b1a5ea2c1818d5f4");
        ButterKnife.bind(this, view);
        Bitmap hh = Code.getInstance().createBitp();
        ivPicCode.setImageBitmap(hh);
        realCode = Code.getInstance().getCode().toLowerCase();
        Log.d("UsernameLoginFragment", realCode);
        return view;
    }

    private void refreshPicCode() {
        ivPicCode.setImageBitmap(Code.getInstance().createBitp());
        realCode = Code.getInstance().getCode().toLowerCase();
    }
    @OnClick({R.id.iv_pic_code, R.id.tv_termOfService, R.id.u_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_pic_code:                                          //图片验证码点击事件
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshPicCode();
                    }
                }, 900);

                break;
            case R.id.tv_termOfService:
                Utils.showSnackBar(getContext(), view, "服务条款");
                break;
            case R.id.u_login:
                currentName = etUsername.getText().toString().trim();                           //去除空格,获取用户名
                currentPassword = etPassword.getText().toString().trim();                       //去除空格，获取密码
                //加密
                //String desEncryptName = DESUtil.des(currentName, currentPassword, Cipher.ENCRYPT_MODE);
                //去除空格，获取图片验证码
                currentPicCode = etPicCode.getText().toString().trim();
                if (TextUtils.isEmpty(currentName) || TextUtils.isEmpty(currentPassword)) {     //判断用户名和密码是否
                    Toast.makeText(getContext(), "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                } else if (realCode.equals(currentPicCode)) {
                    //等待动画
                    pd = new ProgressDialog(getContext());
                    pd.setMessage("正在登陆...");
                    pd.show();
                    if (BmobUser.isLogin()) {
                        User user = BmobUser.getCurrentUser(User.class);
                        Toast.makeText(getContext(), "已经登录：" + user.getUsername(), Toast.LENGTH_SHORT).show();
                        pd.dismiss();
                    } else {
                        Log.d("UsernameLoginFragment", "currentName:" + currentName);
                        Log.d("UsernameLoginFragment", "currentPassword:" + currentPassword);
                        loginByAccount(view, currentName, currentPassword);
                    }
                } else {
                    Toast.makeText(getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 账号密码登录
     */
    private void loginByAccount(final View view, String username, String password) {
        BmobUser.loginByAccount(username, password, new LogInListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e == null) {
                    pd.dismiss();
                    startMainActivity();
                } else {
                    pd.dismiss();
                    refreshPicCode();
                    Log.d("UsernameLoginFragment", "username:" + username + ",password:" + password);
                    Utils.showSnackBar(getContext(), view, "用户名或密码错误");
                }
            }
        });
    }

    /**
     * 手机号码密码登录
     */
    private void loginByPhone(View view, String phone, String password){

        BmobUser.loginByAccount(phone, password, new LogInListener<User>() {

            @Override
            public void done(User user, BmobException e) {
                if(user!=null){
                    if (e == null) {
                        pd.dismiss();
                        Utils.showSnackBar(getContext(), view, "短信登录成功：" + user.getObjectId() + "-" + user.getUsername());
                    } else {
                        Utils.showSnackBar(getContext(), view, "短信登录失败");
                        Log.d("UsernameLoginFragment", "短信登录失败：" + e.getErrorCode() + "-" + e.getMessage());
                    }
                }
            }

        });
    }

    /**
     * 邮箱+密码登录
     */
    private void loginByEmailPwd(View view, String email, String password) {
        BmobUser.loginByAccount(email,password, new LogInListener<User>() {

            @Override
            public void done(User user, BmobException e) {
                if (e == null) {
                    pd.dismiss();

                    Utils.showSnackBar(getContext(), view, "邮箱登录成功：" + user.getObjectId() +"-"+user.getUsername());
                    startMainActivity();
                } else {
                    Log.e("BMOB", e.toString());
                    Utils.showSnackBar(getContext(), view, "邮箱登录失败：" + e.getErrorCode() + "-" + e.getMessage());
                }
            }
        });
    }

    private void startMainActivity() {
        startActivity(new Intent(getContext(), MainActivity.class));
        if (getContext() != null) {
            ((LoginActivity)getContext()).finish();
        }

    }
}